package cn.qingyun.gis.modules.express.util;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharPool;
import cn.hutool.crypto.digest.DigestUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.express.util.constants.StrContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author WeiXiang
 * @Description ：签名工具类
 */
@Slf4j
public class UbopSignUtil {


    /**
     * H5接入生成get请求UbopSign
     *
     * @param url    入参url,示例：https://testsd.cicd.vpclub.cn/mcs/login/app/open/ubop/auth/redirect?
     *               employeeNumber=0000006t&phone=31013026a6d2a140f814fa80d9c5ccdc&timestamp=1622451
     *               479318&uesrName=31ba8f4c094abef6ec84071ef9ab7120&ubopSign=471CBC3DF53CE972D3B84C
     *               C53718A7DF
     * @param aesKey 商户aes密钥
     * @return 签名UbopSign
     */
    public static String creatGetUbopSign(String url, String aesKey) {
        //处理URL，ascII 排序
        TreeMap<String, String> stringStringTreeMap = URLUtil.parsingURLToUri(url);
        if (MapUtil.isEmpty(stringStringTreeMap)) {
            return null;
        }
        //组装参数
        stringStringTreeMap.remove("ubopSign");
        StringBuilder param = new StringBuilder();
        for (Map.Entry<String, String> stringStringEntry : stringStringTreeMap.entrySet()) {
            param.append(stringStringEntry.getKey()).append(StrContext.EQ).append(stringStringEntry.getValue()).append(CharPool.AMP);
        }
        param.append(StrContext.AESKEY).append(aesKey);
        //生成签名
        String encryptionValue = DigestUtil.md5Hex(param.toString());
        return encryptionValue.toUpperCase();
    }


    /**
     * 校验 GET请求签名
     *
     * @param url    同上
     * @param aesKey 商户aes密钥
     * @return 签名是否正确，true  or false
     */
    public static boolean checkGetUbopSign(String url, String aesKey) {
        boolean flag = false;
        try {
            //处理URL，ascii 排序
            TreeMap<String, String> stringStringTreeMap = URLUtil.parsingURLToUri(url);
            if (MapUtil.isEmpty(stringStringTreeMap)) {
                return flag;
            }
            String timestamp = stringStringTreeMap.get("timestamp");
            //当前时间
            long timeMillis = System.currentTimeMillis();
            //判断校验签名时间与url请求时间差
            long timeDifference = DateUtil.between(new Date(Long.parseLong(timestamp)), new Date(timeMillis), DateUnit.MINUTE);
            if (timeDifference > 10) {
                throw new CommonException("时间校验过期， 请退出重新登录");
            }
            //获取请求中的签名
            String urlUbopSign = stringStringTreeMap.get("ubopSign");
            //生成新的签名
            String creatUbopSign = creatGetUbopSign(url, aesKey);
            assert creatUbopSign != null;
            if (creatUbopSign.equals(urlUbopSign)) {
                flag = true;
            }
        } catch (Exception e) {
            log.error("接口签名校验失败，", e);
        }
        return flag;
    }
}
